package com.mhstay.portlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Locale;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.servlet.http.HttpServletRequest;

import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.servlet.SessionMessages;
import com.liferay.portal.kernel.util.Constants;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.model.Contact;
import com.liferay.portal.model.User;
import com.liferay.portal.service.ContactLocalServiceUtil;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.service.ServiceContextFactory;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.PwdGenerator;
import com.liferay.util.bridges.mvc.MVCPortlet;
import com.mhstay.util.IConstants;

public class RegisterPortlet extends MVCPortlet {

	public void createHost(ActionRequest actionRequest,
			ActionResponse actionResponse) throws IOException, PortletException {
		
		String firstName = ParamUtil.getString(actionRequest, "firstName");
		String lastName = ParamUtil.getString(actionRequest, "lastName");
		String emailAddress = ParamUtil.getString(actionRequest, "emailAddress");
		boolean male = ParamUtil.getBoolean(actionRequest, "gender", true);
		
		long companyId = PortalUtil.getCompanyId(actionRequest);
		long creatorUserId = 0l;
		try {
			creatorUserId = UserLocalServiceUtil.getDefaultUserId(companyId);
		} catch (PortalException e) {
			e.printStackTrace();
		} catch (SystemException e) {
			e.printStackTrace();
		}
		
		ServiceContext serviceContext = null;
		try {
			serviceContext = ServiceContextFactory.getInstance(actionRequest);
		} catch (PortalException e) {
			e.printStackTrace();
		} catch (SystemException e) {
			e.printStackTrace();
		}
		
		User user = null;
		try {
			user = UserLocalServiceUtil.addUserWithWorkflow(creatorUserId,
					companyId, true, StringPool.BLANK, StringPool.BLANK, true,
					StringPool.BLANK, emailAddress, 0, StringPool.BLANK, Locale.US,
					firstName, StringPool.BLANK, lastName, 0, 0, male,
					1, 1, 1, StringPool.BLANK, null,
					null, null, null, true,
					serviceContext);
		} catch (PortalException e) {
			e.printStackTrace();
		} catch (SystemException e) {
			e.printStackTrace();
		}
		
		System.out.println("user successfully created...." + user);
		
		saveExtraInfo(actionRequest, user);
		
		HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest);
		
		if (ParamUtil.getBoolean(actionRequest, "host", false)) {
			user.setOpenId("host");
			try {
				user = UserLocalServiceUtil.updateUser(user);
			} catch (SystemException e) {
				e.printStackTrace();
			}
		}

		SessionMessages.add(request, "userAdded", user.getEmailAddress());
		
		ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest
				.getAttribute(WebKeys.THEME_DISPLAY);
		actionResponse.sendRedirect(themeDisplay.getURLSignIn());
	}

	private void saveExtraInfo(ActionRequest actionRequest, User user) {
		
		long nationality = ParamUtil.getLong(actionRequest, "nationality");
		String idd = ParamUtil.getString(actionRequest, "idd");
		String mobile = ParamUtil.getString(actionRequest, "mobileNumber");
		
		// saving the additional information. 
		Contact contact = null;
		try {
			contact = user.getContact();
		} catch (PortalException e) {
			e.printStackTrace();
		} catch (SystemException e) {
			e.printStackTrace();
		}
		
		if (Validator.isNotNull(contact)) {
			contact.setMiddleName(String.valueOf(nationality));
			contact.setEmployeeNumber(idd + StringPool.DASH + mobile);
			
			String pinNumber = PwdGenerator.getPinNumber();
			contact.setJobClass(pinNumber);
			
			try {
				ContactLocalServiceUtil.updateContact(contact);
			} catch (SystemException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void serveResource(ResourceRequest resourceRequest,
			ResourceResponse resourceResponse) throws IOException,
			PortletException {
		
		String cmd = ParamUtil.getString(resourceRequest, Constants.CMD);
		
		if (cmd.equalsIgnoreCase(IConstants.CMD_CHECK_DUPLICATE)) { 
			long companyId = PortalUtil.getCompanyId(resourceRequest);

			String emailAddress = ParamUtil.getString(resourceRequest, "emailAddress");
	        PrintWriter writer = resourceResponse.getWriter();
	        writer.println(isEmailExists(companyId, emailAddress));
	        writer.flush();
		}
    }

	private boolean isEmailExists(long companyId, String emailAddress) {
		boolean exists = false;
		
		try {
			User user = UserLocalServiceUtil.fetchUserByEmailAddress(companyId, emailAddress);
			
			exists = Validator.isNotNull(user);
		} catch (SystemException e) {
			e.printStackTrace();
		}
		
		return exists;
	}
}